#!/bin/bash

if [ `arch` = "aarch64" ];then
        ARCH=arm64
elif [ `arch` = "x86_64" ];then
        ARCH=amd64
elif [ `arch` = "mips64" ];then
        ARCH=mips64
elif [ `arch` = "sw_64" ];then
        ARCH=sw64
else
        ARCH=unknow
fi

source $(dirname $0)/version
rm -rf $(dirname $0)/../dist/* > /dev/null 2>&1
rm -rf /tmp/system-charts
REPO=harbor.sh.deepin.com/$ARCH
TAG=uos
rm -rf ~/bin/ && mkdir ~/bin/ && sudo cp $(dirname $0)/../bin/data.json ~/bin/
set -e

SYSTEM_CHART_DEFAULT_BRANCH=${SYSTEM_CHART_DEFAULT_BRANCH:-"release-v2.4"}
cd $(dirname $0)/../package
cp ../bin/rancher ../bin/agent ../bin/data.json .

IMAGE=${REPO}/rancher:${TAG}
AGENT_IMAGE=${REPO}/rancher-agent:${TAG}

#Don't know if this is needed, uncomment when neccessary
#export RANCHER_METADATA_BRANCH=$VERSION
#if [ ${ARCH} != amd64 ]; then
#    sed -i -e '$a\' -e 'ENV ETCD_UNSUPPORTED_ARCH=$ARCH' Dockerfile
#fi

docker build --build-arg VERSION=${TAG} --build-arg ARCH=${ARCH} --build-arg IMAGE_REPO=${REPO} -t ${IMAGE} .
docker build --build-arg VERSION=${TAG} --build-arg ARCH=${ARCH} -t ${AGENT_IMAGE} -f Dockerfile.agent .
echo ${IMAGE} > ../dist/images
echo ${AGENT_IMAGE} >> ../dist/images
echo Built ${IMAGE} #${AGENT_IMAGE}
echo

cd ../bin
mkdir -p /tmp/system-charts && git clone --branch $SYSTEM_CHART_DEFAULT_BRANCH https://github.com/rancher/system-charts /tmp/system-charts
echo TAG=$TAG REPO=${REPO} go run ../pkg/image/export/main.go /tmp/system-charts $IMAGE $AGENT_IMAGE
TAG=$TAG REPO=${REPO} go run ../pkg/image/export/main.go /tmp/system-charts $IMAGE $AGENT_IMAGE
